package interview;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Leetcode_面试题_29 {
    public int[] spiralOrder(int[][] matrix) {
        List<Integer> l = new LinkedList<>();
        if (matrix == null || matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 0)) {
            return new int[]{};
        }
        int[][] a = new int[matrix.length][matrix[0].length];
        int flag = 0, i = 0, j = 0, r = matrix.length - 1, c = matrix[0].length - 1;

        while (a[i][j] == 0) {
            l.add(matrix[i][j]);
            a[i][j] = 1;
            if (i == 0 && j < c) {
                j++;
            } else if (j == c && i < r) {
                i++;
            } else if (i == r && j > 0) {
                j--;
            } else if (j == 0 && i > 1) {
                i--;
            } else if (r > 1 && c > 1) {
                if (flag == 0) {
                    if (a[i][j + 1] == 0) {
                        j++;
                    } else {
                        i++;
                        flag = 1;
                    }
                } else if (flag == 1) {
                    if (a[i + 1][j] == 0) {
                        i++;
                    } else {
                        j--;
                        flag = 2;
                    }
                } else if (flag == 2) {
                    if (a[i][j - 1] == 0) {
                        j--;
                    } else {
                        i--;
                        flag = 3;
                    }
                } else if (flag == 3) {
                    if (a[i - 1][j] == 0) {
                        i--;
                    } else {
                        j++;
                        flag = 0;
                    }
                }
            }
        }
        return l.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void main(String[] args) {

    }
}
